﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GrayParrot.ServiceBus;
using GrayParrot.ServiceBus.Configuration;
using GrayParrot.Core.Serialization;

using ConsoleApplication1;
using GrayParrot.Core;

namespace TestDelayedService
{
    public class TestDelayedSubscriber : GrayParrot.ServiceBus.Subscriber<TestDelayedSubscriber>
    {
        public TestDelayedSubscriber()
            : base("TestDelayed")
        {

        }

        public override void Receive(Microsoft.ServiceBus.Messaging.BrokeredMessage message)
        {
            //
            //BrokeredMessage msg = new BrokeredMessage();
            //ReturnValue<DelayedMessageStatus> m_res = msg.IsDelayed();

            var m_msgBody = message.GetBody<string>();

            if (message.ScheduledEnqueueTimeUtc != default(DateTime))
            {
                Console.WriteLine("IsDelayed 1");
            }

            ServiceBusMessageBag<BufferRemoveMessage> m_bfrMsg = m_msgBody.DeserializeAsXml<ServiceBusMessageBag<BufferRemoveMessage>>();

            if (m_bfrMsg.IsDelayed)
            {
                Console.WriteLine("IsDelayed 2");
            }

            ReturnValue<bool> m_res = m_bfrMsg.CheckDelayed();

            if (m_res.HasValue && m_res.Value)
            {
                ReturnValue<bool> m_resDC = m_bfrMsg.IsDelayedCancelled();

                if (m_resDC.HasValue && !m_resDC.Value)
                {
                    ReturnValue<bool> m_res1 = m_bfrMsg.SetDelayedMessageCancelled();
                    Console.WriteLine(m_res1.Value);
                }
            }
            else
            {
                if (m_res.HasError)
                {
                    Console.WriteLine("Errore: {0}", m_res.Error.Message);
                }
                else
                {
                    Console.WriteLine("Errore: {0}", m_res.Message);
                }
            }

            System.Threading.Thread.Sleep(2000);
        }

        public ReturnValue<DelayedMessageStatus> IsDelayed2(Microsoft.ServiceBus.Messaging.BrokeredMessage msg)
        {
            ReturnValue<DelayedMessageStatus> retValue = new ReturnValue<DelayedMessageStatus>(DelayedMessageStatus.None);

            try
            {
                GrayParrot.Configuration.ConfigurationManagerHelper pp = new GrayParrot.Configuration.ConfigurationManagerHelper();
                DelayedMessagesSettings m_dms = pp.GetDelayedMessagesSetting();

                string m_sqlCommand = string.Format("SELECT Status FROM {0}.{1} WHERE MessageId='{2}'", m_dms.SchemaName, m_dms.TableName, Guid.Parse(msg.MessageId));

                string cn = System.Configuration.ConfigurationManager.ConnectionStrings[m_dms.ConnectionStringName].ConnectionString;

                using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(cn))
                {
                    connection.Open();

                    DelayedMessageStatus m_status = DelayedMessageStatus.New;
                    using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(m_sqlCommand, connection))
                    {
                        using (System.Data.SqlClient.SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                m_status = (DelayedMessageStatus)Enum.Parse(typeof(DelayedMessageStatus), reader["Status"].ToString());

                                retValue.HasValue = true;
                                retValue.Value = m_status;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                retValue.HasError = true;
                retValue.Error = ex;
            }

            return retValue;
        }
    }
}
